package com.itheima.health.service.impl;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.service.VerificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;


@Service
public class VerificationServiceImpl implements VerificationService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final long EXPIRATION_TIME = 5 * 60; // 过期时间5分钟

    private static final long REPEAT_TIME =  60; // 短信验证码限制1分钟1次
    @Override
    public Result sendVerificationCode(String type, String phoneNumber, String code) {
        String key = type+ ":" + phoneNumber;

        HashOperations<String, Object, Object> ops = redisTemplate.opsForHash();
        String last_sent_time = String.valueOf(System.currentTimeMillis());

        String expiry_time = String.valueOf(System.currentTimeMillis() + EXPIRATION_TIME * 1000);
        // 存储验证码和发送时间
        ops.put(key, "code", code);
        ops.put(key, "last_sent_time", last_sent_time);
        ops.put(key, "expiry_time",expiry_time );
        return null;
    }
    @Override
    public Boolean verifyCodeRepeat(String type, String phoneNumber){
        String key = type+ ":" + phoneNumber;
        System.out.println(redisTemplate.hasKey(key));
        if(redisTemplate.hasKey(key)){
            HashOperations<String, String, String> ops = redisTemplate.opsForHash();
            Long last_sent_time = Long.parseLong(ops.get(key,"last_sent_time"));
            if(System.currentTimeMillis()-last_sent_time<(REPEAT_TIME*1000)){
                return false;
            }
        }
        return true;
    }
    @Override
    public Result verifyCode(String type, String phoneNumber, String code) {
        String key = type+ ":" + phoneNumber;
        HashOperations<String, String, String> ops = redisTemplate.opsForHash();
        String storedCode = ops.get(key, "code");
        Long expiryTime = Long.parseLong(ops.get(key,"expiry_time"));
        if(!redisTemplate.hasKey(key)){
            return new Result(false, MessageConst.TELEPHONE_NOT_PRESENT);
        }
        if( System.currentTimeMillis() > expiryTime){
            return new Result(false, MessageConst.TELEPHONE_VALIDATECODE_EXPIRE);
        }
        // 检查验证码是否匹配以及是否未过期
        return new Result(true,MessageConst.LOGIN_SUCCESS );
    }
}
